package androidserver.servlets.uploader;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import androidserver.control.Control;
import androidserver.exceptions.MyJSONException;
import androidserver.jsonprocessor.JSONProcessor;
import androidserver.jsonprocessor.json.JSONException;
import androidserver.jsonprocessor.json.JSONObject;

@WebServlet("/UploadFile")
public class UploaderServlet extends HttpServlet {
	private static final long serialVersionUID = 7272013633035193593L;

	public UploaderServlet() {
		super();
	}

	public void doPost(HttpServletRequest req, HttpServletResponse res) {

		String strJson = req.getParameter("jsonUpload");
		System.out.println("dopost:" + strJson + "_");
		JSONProcessor jsonProcessor = new JSONProcessor();
		JSONObject jsonRequest = null;
		JSONObject jsonResponse = new JSONObject();
		try {
			jsonRequest = jsonProcessor.processJSONString(strJson);
		} catch (MyJSONException e) {
			e.printStackTrace();
			jsonResponse = new JSONObject();
			try {
				jsonResponse.put("err", e.getMessage());
			} catch (JSONException e1) {
				e1.printStackTrace();
			}
		}

		if (jsonRequest != null){
			try {
				jsonResponse = Control.getInstance().processRequest(jsonRequest);
			} catch (MyJSONException e) {
				e.printStackTrace();
				jsonResponse = new JSONObject();
				try {
					jsonResponse.put("err", e.getMessage());
				} catch (JSONException e1) {
					e1.printStackTrace();
				}
			}
		}

		PrintWriter out;
		try {
			out = res.getWriter();
			out.println(jsonResponse.toString());
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

}
